package com.hx.controller;

import com.hx.entity.BaseTemplateVO;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@RestController(value = "文档转换")
@Api(value = "文档转换")
@RequestMapping("/api")
public class HandleController {
    @GetMapping("/wsdl/save")
    public void saveWsdl() {
        RestTemplate template = new RestTemplate();
        ResponseEntity<String> response = template.getForEntity("http://localhost:8080/test?wsdl", String.class);
        String body = response.getBody();
        String strFilename = "D:\\work\\project".concat("\\test.WSDL");
        saveFile(strFilename, body);
    }

    public void saveFile(String strFilename, String strBuffer) {
        try {
            // 创建文件对象
            File fileText = new File(strFilename);
            // 向文件写入对象写入信息
            FileWriter fileWriter = new FileWriter(fileText);

            // 写文件
            fileWriter.write(strBuffer);
            // 关闭
            fileWriter.close();
        } catch (IOException e) {
            //
            e.printStackTrace();
        }
    }

    /**
     * MultipartFile 默认尺寸不能超过1MB  如果需要传大文件 需要在配置文件里设置
     */
    @ApiOperation(value = "word转pdf")
    @PostMapping("/wordToPdf")
    public ResponseEntity wordToPdf(@RequestParam("srcPath") String srcPath,
                                    @RequestParam("outPath") String outPath) throws IOException {
        // 以下为文件转换为PDF
        try {
            XWPFDocument document = new XWPFDocument(new FileInputStream(new File(srcPath)));
            PdfOptions options = PdfOptions.create();
            PdfConverter.getInstance().convert(document, Files.newOutputStream(Paths.get(outPath)), options);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.ok().build();
    }

    @ApiOperation(value = "根据word模板创建文档")
    @PostMapping("/creat/word/baseTemplate")
    public ResponseEntity baseTemplate(@RequestBody @Validated @ApiParam(value = "替换参数") BaseTemplateVO baseTemplateVO) throws IOException {
        String srcPath = baseTemplateVO.getSrcPath();
        String outPath = baseTemplateVO.getOutPath();
        Map<String, Object> map = baseTemplateVO.getMap();
        searchAndReplace(srcPath, outPath, map);
        if (baseTemplateVO.getIsOutPdf()) {
            String pdfPath = outPath.replace(".docx", ".pdf");
            XWPFDocument document = new XWPFDocument(new FileInputStream(new File(outPath)));
            PdfOptions options = PdfOptions.create();
            PdfConverter.getInstance().convert(document, Files.newOutputStream(Paths.get(pdfPath)), options);
        }
        return ResponseEntity.ok("根据word模板创建文档成功！");
    }

    /**
     * 将word模板中的文字进行替换
     */
    public static void searchAndReplace(String srcPath, String destPath, Map<String, Object> map) {
        try {
            // 替换的的关键字存放到Set集合中
            Set<String> set = map.keySet();
            // 读取模板文档
            XWPFDocument document = new XWPFDocument(new FileInputStream(srcPath));
            /**
             * 替换段落中的指定文字
             */
            // 读取文档中的段落，回车符为一个段落。
            // 同一个段落里面会被“:”等符号隔开为多个对象
            Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
            while (itPara.hasNext()) {
                // 获取文档中当前的段落文字信息
                XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
                List<XWPFRun> run = paragraph.getRuns();
                // 遍历段落文字对象
                for (int i = 0; i < run.size(); i++) {
                    // 获取段落对象
                    if (run.get(i) == null) {    //段落为空跳过
                        continue;
                    }
                    String sectionItem = run.get(i).getText(run.get(i).getTextPosition());    //段落内容
                    // 遍历自定义表单关键字，替换Word文档中的内容
                    Iterator<String> iterator = set.iterator();
                    while (iterator.hasNext()) {
                        // 当前关键字
                        String key = iterator.next();
                        // 替换内容
                        if (sectionItem==null) {
                            continue;
                        }
                        sectionItem = sectionItem.replace(key, String.valueOf(map.get(key)));
                    }
                    run.get(i).setText(sectionItem, 0);
                }
            }

            /**
             * 替换表格中的指定文字
             */
            //获取文档中所有的表格，每个表格是一个元素
            Iterator<XWPFTable> itTable = document.getTablesIterator();
            while (itTable.hasNext()) {
                XWPFTable table = (XWPFTable) itTable.next();   //获取表格内容
                int count = table.getNumberOfRows();    //表格的行数
                //遍历表格行的对象
                for (int i = 0; i < count; i++) {
                    XWPFTableRow row = table.getRow(i);    //表格每行的内容
                    List<XWPFTableCell> cells = row.getTableCells();   //每个单元格的内容
                    //遍历表格的每行单元格对象
                    for (int j = 0; j < cells.size(); j++) {
                        XWPFTableCell cell = cells.get(j);    //获取每个单元格的内容
                        List<XWPFParagraph> paragraphs = cell.getParagraphs();      //获取单元格里所有的段落
                        for (XWPFParagraph paragraph : paragraphs) {
                            //获取段落的内容
                            List<XWPFRun> run = paragraph.getRuns();
                            // 遍历段落文字对象
                            for (int o = 0; o < run.size(); o++) {
                                // 获取段落对象
                                if (run.get(o) == null || run.get(o).equals("")) {
                                    continue;
                                }
                                String sectionItem = run.get(o).getText(run.get(o).getTextPosition());    //获取段落内容
                                if (sectionItem == null || sectionItem.equals("")) {    //段落为空跳过
                                    continue;
                                }
                                //遍历自定义表单关键字，替换Word文档中表格单元格的内容
                                for (String key : map.keySet()) {
                                    // 替换内容
                                    sectionItem = sectionItem.replace(key, String.valueOf(map.get(key)));
                                    run.get(o).setText(sectionItem, 0);
                                }
                            }
                        }
                    }
                }
            }
            FileOutputStream outStream = null;
            outStream = new FileOutputStream(destPath);
            document.write(outStream);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}